<?php
/**
 * 分销服务层
 * User: 陈立强
 * Date: 2019/11/8
 * Time: 11:39
 */


namespace app\common\service;

use app\common\logic\Dump;
use app\common\model\MemberYongjin;
use app\facade\Members as MembersFacade;//用户静态处理层
use app\common\model\Members as MembersModel;//用户模型
use app\common\model\Orders as OrdersModel;//订单模型
use app\common\model\OrderGoods as OrderGoodsModel;//订单产品详情模型
use app\common\model\MemberCash as MemberCashModel;//用户提现模型
use app\common\model\MemberYongjin as MemberYongjinModel;//用户佣金模型
use app\common\model\MembersDistribution as MembersDistributionModel;//用户分销申请模型
use app\facade\Options AS OptionsFacade;//配置静态处理层
use think\facade\Cache;
use think\facade\Env;
class Distribution extends Base

{
    /*
     * 分销配置
     *
     * $data  string  配置参数名称
     * */
    public function distribution_cofing($data){
        $key   = md5('distribution_info');

        $options  = Cache::get($key);

        if (!$options) {
            $options = unserialize(OptionsFacade::option('distribution_info'));
            Cache::tag('distribution_info')->set($key, $options);
        }

        $cofing = $options[$data];

        return $cofing;
    }

    /*
    * 成为分销商
    *
    * $userid  int  用户ID
    * */
    public function is_distribution($userid){
        $user = MembersModel::where('id',$userid)->field('id,is_distribution,referral_code')->find();//查询信息
        if($user['is_distribution']  == 0){
            $return = $this->is_distributions($userid);
            if($return == 1){

                $user->is_distribution = 1;//成为分销商
                $user->referral_code = $this->referral_code();//分销商推荐码
                $user->save();
            }
        }
        return 1;
    }


    /*
     * 是否可成为分销商
     *
     * $userid  int  用户ID
     * */
    public function is_distributions($userid){
        $cofing = $this->distribution_cofing('commission_become');
        if($cofing == 0){//无条件
            return 1;
        }
        if($cofing == 1){//申请
            $status = MembersDistributionModel::where('userid',$userid)->value('status');
            if($status && $status['status'] == 1){
                return 1;
            }
        }
        if($cofing == 2){//消费次数
            $order_count = $this->distribution_cofing('commission_become_order_count');
            $where = [
                ['userid','eq',$userid],
                ['pay_status','eq',1]
            ];
            $num = OrdersModel::where($where)->count('id');
            if($num >= $order_count){
                return 1;
            }
        }
        if($cofing == 3){//消费额度
            $money_count = $this->distribution_cofing('commission_become_money_count');
            $where = [
                ['userid','eq',$userid],
                ['pay_status','eq',1]
            ];
            $money = OrdersModel::where($where)->sum('order_amount');
            if($money >= $money_count){
                return 1;
            }
        }
        if($cofing == 4){//购买商品
            $goods_id = $this->distribution_cofing('commission_become_goods_id');
            $where = [
                ['userid','eq',$userid],
                ['pay_status','eq',1]
            ];
            $order = OrdersModel::where($where)->field('GROUP_CONCAT(id) as order_id')->select();
            $where_g = [
                ['order_id','in',$order['order_id']],
                ['goods_id','eq',$goods_id]
            ];
            $order_goods = OrderGoodsModel::where($where_g)->field('id')->select();
            if($order_goods){
                return 1;
            }
        }
        return 0;
    }

    /*
     * 分销商推荐码
     * */
    public function referral_code(){
        for ($i=1;$i<1000;$i++){
            $referral_code = rand(100000,999999);
            $member = MembersModel::where('referral_code',$referral_code)->value('id');
            if(!$member){
                return $referral_code;
            }
        }
    }
    /*
     * 分销商提交申请
     *  $data  array  申请信息
     * */
    public function distribution_apply($data){
        $is_check = $this->distribution_cofing('commission_become_check');
		$info = MembersDistributionModel::where('userid',$data['userid'])->value('id');
        if($info){
        	exception('您已申请过不用重复申请');
		}
        if($is_check == 0){
            $data['status'] = 1;
            MembersModel::update(['id'=>$data['userid'],'is_distribution'=>1]);
        }
        $data['create_time'] = time();
        $create = MembersDistributionModel::create($data);
        return 1;
    }

    /*
         * 成为下线
         *
         * $userid int  用户ID
         * $parent_id int  上级ID
         * */
    public function can_offline($userid,$parent_id){
        $user = MembersModel::where('id',$userid)->field('id,parent_id,is_binding,distribution_num')->find();//查询信息
        if($userid == $parent_id){//判断上级ID是否和用户ID相同
            $parent_id =0;
        }else{
            $parent = MembersModel::where('id',$parent_id)->field('id,parent_id,distribution_num')->find();//查询上级信息
            if(!$parent){//判断上级ID是否真实有效
                $parent_id = 0;
            }else{
				if($parent['parent_id'] == $userid){//判断上级的上级是否是用户本身
					$parent_id = 0;
				}
			}
        }

        if($user['is_binding'] == 0 && ($parent_id >0 || $user['parent_id'] > 0)){//判断用户是否未成功绑定并存在上级ID
            $return = $this->canoffline($userid);
            if($return == 1){
                if($parent_id > 0){
                    $user->parent_id = $parent_id;//重新分配上级
                }

                $user->is_binding = 1;//确认绑定为上下级
                $user->save();
                $parent->distribution_num = ['inc',1];//下级人数加1

                $parent->save();

                MembersFacade::add_messge($parent_id,'您有一个下级注册成功');
            }
        }

        return 1;
    }

    /*
     * 成为下线条件
     *
     * $userid int  用户ID
     * */
    public function canoffline($userid){
        $can_offline = $this->distribution_cofing('commission_become_child');
        if($can_offline == 1){//无条件
            return 1;
        }
        if($can_offline == 2){//首次下单
            $where = [
                ['userid','eq',$userid]
            ];
            $order = OrdersModel::where($where)->value('id');
            if($order){
                return 1;
            }

        }
        if($can_offline == 3){//首次支付
            $where = [
                ['userid','eq',$userid],
                ['pay_status','eq',1]
            ];
            $order = OrdersModel::where($where)->value('id');
            if($order){
                return 1;
            }
        }

        return 0;

    }

    /*
     * 我的下级
     *
     * $uid   int       会员id
     * $type  int       判断1级列表还是2级列表
     * $limit string    分页
     *
     * */
    public function distribution_member($uid,$type,$limit){

        $info = MembersModel::field('username,nickname,id,wechat_id,create_time')
            ->append(['headimgurl'])->where('parent_id', $uid)->where('is_binding',1)->limit($limit)->select()->toArray();
        $data=[];
        if (!empty($info)) {
            if ($type == 1) {//一级
                $data = $info;
            }else{//二级
                foreach ($info as $key => $val){
                    $ids[$key] = $val['id'];
                }
                $infos = MembersModel::field('username,nickname,id,wechat_id,create_time')
                    ->append(['headimgurl'])->where('parent_id','in', $ids)->where('is_binding',1)->limit($limit)->select()->toArray();
                $data = $infos;
            }
        }
        return $data;

    }


    /*
     * 分销订单
     *
     * $userId  int     用户ID
     * $limit   string  分页
     * */
    public function distribution_order($userId, $limit){
        $where[] = [
            ['userid', 'in', $userId],
            ['order_status', 'eq', 255],

        ];
        $data = OrdersModel::field('id,userid,order_type,order_no,pay_type,order_amount,pay_amount,balance,points,vouchers,order_status,pay_status,shipping_status,pay_time,send_time,sign_time,create_time,finish_time')
            ->append(['order_status_id', 'order_status_txt', 'goods_list','user_info'])->where($where)->order('id DESC')->limit($limit)->select();

        return $data;
    }

    /*
    * 佣金记录
    *
     * $uid     int    会员ID
     *
     * $limit   int   分页
     *
    * */
    public function distribution_list($uid,$limit){

        $data = MemberYongjinModel::field(true)->where('userid', $uid)->limit($limit)->select()->toArray();

        return $data;
    }

    /*
     * 佣金提现
     *
     * $data    array   提现数据
     * */
    public function distribution_cash($data){
        $withdraw_type = $data['withdraw_type'];//提现方式
        $money = (float)$data['money'];//提现金额
        $withdraw_least = $this->distribution_cofing('commission_withdraw_least');//最低提现额度
        $withdraw_charge = $this->distribution_cofing('commission_withdraw_charge');//提现手续费

        $member = MembersModel::field('id,money')->where('id', $data['userid'])->find();

        if ($money > $member['money']) {

            exception('提现金额不足');

        }

        if($money < $withdraw_least){
            exception( '余额不足');
        }
        $data['amount'] = $money;//支付金额
        $data['charge'] = 0;
        if($withdraw_charge > 0){
            $data['charge'] = round($money * $withdraw_charge *0.01,2);//手续费
            $data['amount'] = $money - $data['charge'];
        }
        if($withdraw_type == 1){//微信
            $time = date('Y-m-d 00:00:00');
            $where = [
                ['userid','eq',$data['userid']],
                ['exam_time','egt',$time],
                ['type','eq',1],
                ['status','eq',1],
            ];
            $cash_money = MemberCashModel::where($where)->sum('amount');//当日微信提现金额
            $weixin_money = 5000 -$cash_money;
            if($data['amount'] > $weixin_money){
                exception( '今日微信提额已达上限');
            }

            $create = [

                'userid' => $data['userid'],    //用户ID

                'wechat_id' => $data['userid'],

                'money' => $money,              //提现金额

                'amount' => $data['amount'],    //支付金额

                'charge' => $data['charge'],    //手续费

                'type' => 1,                    //提现方式

                'is_app' =>$data['is_app'],     //判断是哪端提现 0 公众号 1 app 2 小程序

                'apply_time' => time()          //提现时间

            ];

            $info = MemberCashModel::create($create);

        }
        if($withdraw_type == 2){//支付宝
            $create = [

                'userid' => $data['userid'],    //用户ID

                'wechat_id' => $data['userid'],

                'money' => $money,              //提现金额

                'amount' => $data['amount'],    //支付金额

                'charge' => $data['charge'],    //手续费

                'alipay' => $data['alipay'],    //支付宝账号

                'type' => 2,                    //提现方式

                'is_app' =>$data['is_app'],     //判断是哪端提现 0 公众号 1 app 2 小程序

                'apply_time' => time()          //提现时间

            ];

            $info = MemberCashModel::create($create);

        }
        if($withdraw_type == 3){//银行卡

            $create = [

                'userid' => $data['userid'],    //提现方式

                'wechat_id' => $data['userid'],

                'money' => $money,              //提现金额

                'amount' => $data['amount'],    //支付金额

                'charge' => $data['charge'],    //手续费

                'card_no' => $data['card_no'],  //卡号

                'bank' => $data['bank'],        //开户行

                'name' => $data['name'],        //姓名

                'mobile' => $data['mobile'],    //手机号

                'type' => 3,                    //提现方式

                'is_app' =>$data['is_app'],     //判断是哪端提现 0 公众号 1 app 2 小程序

                'apply_time' => time()          //提现时间
            ];

            $info = MemberCashModel::create($create);
        }
        if($withdraw_type == 4){//商城余额
            $create = [

                'userid' => $data['userid'],    //用户ID

                'wechat_id' => $data['userid'],

                'money' => $money,              //提现金额

                'amount' => $data['amount'],    //支付金额

                'charge' => $data['charge'],    //手续费

                'type' => 4,                    //提现方式

                'is_app' =>$data['is_app'],     //判断是哪端提现 0 公众号 1 app 2 小程序

                'apply_time' => time()          //提现时间

            ];

            $info = MemberCashModel::create($create);
        }

        if ($info) {

            $member->money = $member['money'] - $money;

            if ($member->save()) {

                return true;

            }

        }

        return false;

    }

    /*
     * 佣金提现记录
     *
     * */
    public function distribution_record($userId, $limit)
    {
        $cash_list = MemberCashModel::field('apply_time,money,status,type')
            ->where(['wechat_id' => $userId])
            ->append(['apply_time_date','status_txt'])
            ->limit($limit)
            ->order('id desc')
            ->select()->toArray();

        return $cash_list;

    }

    /*
     * 分销海报
     *
     * $userId  int  用户ID
     *
     * */
    public function distribution_posters($userId){


        $rootPath = str_replace('\\', '/', Env::get('root_path'));
        require $rootPath . 'extend/phpqrcode/phpqrcode.php';
        $file = './static/uploads/qrcode/Info_' . $userId . '.png';
        $value = config('system.attach_uri_prefix') . 'mob/?#/?uid=' . $userId;
//		$content = 'BEGIN:VCARD'."\n";
//		$content .='version:2.1'."\n";
//		$content .='N:吴'."\n"; 	 //姓
//		$content .='FN:DD'."\n";	//名
//		$content .='TEL;WORK;VOICE:123456'."\n"; //工作电话
//		$content .='END:VCARD'."\n";
        $errorCorrectionLevel = "L";
        $matrixPointSize = 10;
        \QRcode::png($value, $file, $errorCorrectionLevel, $matrixPointSize, 2);
        $data['content'] = $value;
        $data['url'] = config('system.attach_uri_prefix') . ltrim($file, './');
        return $data;

    }


    /*
     * 分销文字
     *
     * $type  int  代表页面 1为 分销中心页  2为佣金中心页
     *
     *  */
    public function distribution_text($type){
        $db['commission_text_center'] = $this->distribution_cofing('commission_text_center');//分销中心
        $db['commission_text_agent'] = $this->distribution_cofing('commission_text_agent');//分销商
        $db['commission_text_charge'] = $this->distribution_cofing('commission_text_charge');//佣金
        $db['commission_text_withdraw'] = $this->distribution_cofing('commission_text_withdraw');//提现
        $db['commission_text_commission_charge'] = $this->distribution_cofing('commission_text_commission_charge');//分销佣金
        $db['commission_text_visible_withdraw_charge'] = $this->distribution_cofing('commission_text_visible_withdraw_charge');//可提现佣金
        $db['commission_text_applied_charge'] = $this->distribution_cofing('commission_text_applied_charge');//已申请佣金
        $db['commission_text_checked_charge'] = $this->distribution_cofing('commission_text_checked_charge');//待打款佣金
        $db['commission_text_withdrew_charge'] = $this->distribution_cofing('commission_text_withdrew_charge');//已提现佣金
        $db['commission_text_unsettled_charge'] = $this->distribution_cofing('commission_text_unsettled_charge');//未结算佣金
        $db['commission_text_invalid_charge'] = $this->distribution_cofing('commission_text_invalid_charge');//无效佣金
        $db['commission_text_child'] = $this->distribution_cofing('commission_text_child');//下线
        $db['commission_text_first_child'] = $this->distribution_cofing('commission_text_first_child');//一级下线
        $db['commission_text_second_child'] = $this->distribution_cofing('commission_text_second_child');//二级下线
        $db['commission_text_third_child'] = $this->distribution_cofing('commission_text_third_child');//三级下线
        $db['commission_text_union'] = $this->distribution_cofing('commission_text_union');//元
        return $db;
    }

    /*
     * 分销结算
     *
     * */
    public function distribution_commission($userid,$order){
        $commission_level = $this->distribution_cofing('commission_level');//分销设置
        if($commission_level > 0){//开启分销
            $member = MembersModel::where('id',$userid)->field('id,parent_id,is_binding,role_id')->append(['role_info'])->find();//用户id,上级ID,是否成功绑定上级
            if($member['parent_id'] >0 && $member['is_binding'] == 1){//判断是否有上级，并且成功绑定
                $commission_charge_type = $this->distribution_cofing('commission_charge_type');//返佣方式  1百分比 0固定金额
                $commission_charge_first = $this->distribution_cofing('commission_charge_first');//返佣比例/金额
				//20200323  修改  分销改为单品设置
				$order_goods = OrdersModel::field('id,goods_id,sale_price,goods_nums')->append(['goods'])->where('id',$order)->select()->toArray();//订单商品列表
				$money_one = 0;//一级佣金
				foreach ($order_goods as $k =>$v){
					$goods_money= 0;
					if($v['goods']['commission_charge_status'] == 1){//是否参与分销
						if($v['goods']['commission_charge_type'] == 0){//商品默认
							if($member['role_info']['commission_charge_type'] == 0){//角色默认
								if($commission_charge_type == 1){
									$goods_money = round($v['sale_price'] * $commission_charge_first *0.01,2);//按照比例返佣
								}else{
									$goods_money = $commission_charge_first;//固定金额
								}
							}elseif($member['role_info']['commission_charge_type'] ==1){
								$goods_money = round($v['sale_price'] * $member['role_info']['commission_charge_first'] *0.01,2);//按照比例返佣
							}else{
								$goods_money = $member['role_info']['commission_charge_first'];//固定金额
							}

						}elseif($v['goods']['commission_charge_type'] ==1){

							$goods_money = round($v['sale_price'] * $v['goods']['commission_charge'][$member['role_id']]['commission_charge_first'] *0.01,2);//按照比例返佣
						}else{
							$goods_money = $v['goods']['commission_charge'][$member['role_id']]['commission_charge_first'];//固定金额
						}
					}
					$money_one += round($goods_money * $v['goods_nums'],2);
				}

                $m_one = array(
                    'id'        => $member['parent_id'],
                    'value'     => $money_one,
                    'remark'    => '下级购买商品返佣',
                    'order_id'  => $order,
                    'status'    => 0,
                );
                $this->commission($m_one);//返佣 修改上一级佣金
                if($commission_level == 2){//判断是否为二级分销
                    $member_one = MembersModel::where('id',$member['parent_id'])->field('id,parent_id,is_binding')->find();//用户id,上级ID,是否成功绑定上级
                    if($member_one['parent_id'] >0 && $member_one['is_binding'] == 1) {//判断是否有上级，并且成功绑定
                        $commission_charge_second = $this->distribution_cofing('commission_charge_second');//返佣比例/金额
						//20200203 修改
						$money_two = 0;//二级佣金
						foreach ($order_goods as $k =>$v){
							$goods_money= 0;
							if($v['goods']['commission_charge_status'] == 1) {//是否参与分销
								if ($v['goods']['commission_charge_type'] == 0) {//商品默认
									if ($member['role_info']['commission_charge_type'] == 0) {//角色默认
										if ($commission_charge_type == 1) {
											$goods_money = round($v['sale_price'] * $commission_charge_second * 0.01, 2);//按照比例返佣
										} else {
											$goods_money = $commission_charge_second;//固定金额
										}
									} elseif ($member['role_info']['commission_charge_type'] == 1) {
										$goods_money = round($v['sale_price'] * $member['role_info']['commission_charge_second'] * 0.01, 2);//按照比例返佣
									} else {
										$goods_money = $member['role_info']['commission_charge_second'];//固定金额
									}

								} elseif ($v['goods']['commission_charge_type'] == 1) {
									$goods_money = round($v['sale_price'] * $v['goods']['commission_charge'][$member['role_id']]['commission_charge_second'] * 0.01, 2);//按照比例返佣
								} else {
									$goods_money = $v['goods']['commission_charge'][$member['role_id']]['commission_charge_second'];//固定金额
								}
							}
							$money_two += round($goods_money * $v['goods_nums'],2);
						}
                        $m_two = array(
                            'id'        => $member_one['parent_id'],
                            'value'     => $money_two,
                            'remark'    => '下级购买商品返佣',
                            'order_id'  => $order,
                            'status'    => 0,
                        );
                        $this->commission($m_two);//返佣 修改上上级佣金
                    }
                }
            }
        }
        return 0;
    }

    /*
     * 修改用户佣金余额
     *
     * $data  array  修改数据信息
     *
     * id           int         用户ID
     * value        double      数值
     * remark       string      备注
     * order_id     int         返佣时订单号ID
     * status       int         状态  0返佣 1提现
     *
     * */
    public function commission($data)

    {
        $id    = (int)$data['id'];

        $key   = 'money';

        $value = $data['value'];

        $remark = isset($data['remark'])?$data['remark']:'管理员后台修改';

        $member = MembersModel::field('id,wechat_id,commission,'.$key)->where('id', $id)->find();

        if (!$member) {

            return;

        }

        $member->$key = ['inc', $value];
        if($key == 'money'){
            $member->commission = ['inc', $value];
        }

        if ($member->save()) {

            $model = '\app\common\model\MemberYongjin';

            $model::create([

                'order_id'    => $data['order_id'],

                'userid'      => $id,

                'wechat_id'    => $id,

                'balance'   => $value,

                'remark'    => $remark,

                'status'      => $data['status'],

                'change_time'      => time(),

            ]);

            return (int)$member->$key + $value;

        }

        return;

    }
    /*
     * 分销排行
     *
     * $userId      int     用户ID
     * */
    public function distribution_ranking($userId){
        $member_mod = new MembersModel();
        $member = $member_mod->getList('','','commission desc','',1,50);
        $ranking = 0;
        foreach ($member as $k =>$v){
            if($v['id'] == $userId){

                $ranking = $k;
            }
        }
        $data['list'] = $member;
        $data['ranking'] = $ranking;

        return $data;
    }

}

